<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>巷陌发现 - 我的打卡记录</title>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
  <style>
    * {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
    }

    body {
      font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif;
      background-color: #f5f7fa;
      color: #333;
      line-height: 1.6;
      padding: 20px 0;
    }

    /* 内容区域样式 */
    .content-container {
      max-width: 1200px;
      margin: 0 auto;
      padding: 0 20px;
    }

    /* 头部区域 */
    .header-section {
      background-color: white;
      border-radius: 12px;
      padding: 25px;
      margin-bottom: 25px;
      box-shadow: 0 5px 15px rgba(0, 0, 0, 0.05);
      display: flex;
      align-items: center;
      justify-content: space-between;
    }

    .user-info {
      display: flex;
      align-items: center;
    }

    .user-avatar {
      width: 70px;
      height: 70px;
      border-radius: 50%;
      background: linear-gradient(45deg, #6a11cb 0%, #2575fc 100%);
      display: flex;
      align-items: center;
      justify-content: center;
      color: white;
      font-size: 28px;
      font-weight: bold;
      margin-right: 15px;
      overflow: hidden;
    }

    .user-avatar img {
      width: 100%;
      height: 100%;
      object-fit: cover;
      border-radius: 50%;
    }

    .user-details h2 {
      font-size: 22px;
      margin-bottom: 5px;
    }

    .user-stats {
      display: flex;
      gap: 15px;
      color: #666;
      font-size: 14px;
    }

    .stat-item {
      display: flex;
      align-items: center;
    }

    .stat-item i {
      margin-right: 5px;
      color: #6a11cb;
    }

    /* 时间线区域 */
    .timeline-section {
      background-color: white;
      border-radius: 12px;
      padding: 25px;
      margin-bottom: 30px;
      box-shadow: 0 5px 15px rgba(0, 0, 0, 0.05);
    }

    .section-title {
      font-size: 20px;
      color: #333;
      margin-bottom: 20px;
      padding-bottom: 10px;
      border-bottom: 2px solid #f0f0f0;
      display: flex;
      align-items: center;
    }

    .section-title i {
      margin-right: 10px;
      color: #6a11cb;
    }

    /* 时间线样式 */
    .timeline {
      position: relative;
      margin-left: 20px;
    }

    .timeline::before {
      content: '';
      position: absolute;
      left: -20px;
      top: 0;
      bottom: 0;
      width: 2px;
      background-color: #e6e6e6;
    }

    .timeline-item {
      position: relative;
      margin-bottom: 30px;
      padding-left: 30px;
    }

    .timeline-item::before {
      content: '';
      position: absolute;
      left: -24px;
      top: 0;
      width: 10px;
      height: 10px;
      border-radius: 50%;
      background-color: #6a11cb;
      z-index: 1;
    }

    .checkin-card {
      background-color: #f8f9fa;
      border-radius: 12px;
      padding: 20px;
      transition: all 0.3s;
      border: 1px solid #eee;
    }

    .checkin-card:hover {
      background-color: white;
      box-shadow: 0 5px 15px rgba(0, 0, 0, 0.08);
    }

    .checkin-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 15px;
    }

    .shop-name {
      font-size: 18px;
      font-weight: bold;
      color: #333;
    }

    .checkin-date {
      color: #888;
      font-size: 14px;
    }

    /* 图片容器样式 - 左对齐正方形网格 */
    .image-container {
      display: flex;
      flex-wrap: nowrap;
      gap: 8px;
      margin-bottom: 15px;
      align-items: flex-start;
    }

    .image-item {
      width: 120px;
      height: 120px;
      position: relative;
      border-radius: 8px;
      overflow: hidden;
      background-color: #f1f1f1;
      cursor: pointer;
      flex-shrink: 0;
      transition: transform 0.2s;
    }

    .image-item:hover {
      transform: scale(1.03);
    }

    .image-item img {
      width: 100%;
      height: 100%;
      object-fit: cover;
      display: block;
    }

    .image-item .image-overlay {
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      background-color: rgba(0, 0, 0, 0.2);
      display: flex;
      align-items: center;
      justify-content: center;
      opacity: 0;
      transition: opacity 0.2s;
    }

    .image-item:hover .image-overlay {
      opacity: 1;
    }

    .image-item .image-overlay i {
      color: white;
      font-size: 20px;
    }

    /* 旧图片容器样式兼容 */
    .checkin-images {
      display: grid;
      grid-template-columns: repeat(3, 1fr);
      gap: 8px;
      margin-bottom: 15px;
      border-radius: 8px;
      overflow: hidden;
    }

    .checkin-image {
      width: 100%;
      height: 100px;
      object-fit: cover;
      border-radius: 6px;
      transition: transform 0.3s;
      cursor: pointer;
    }

    .checkin-image:hover {
      transform: scale(1.05);
    }

    .checkin-content {
      margin-bottom: 15px;
      line-height: 1.6;
    }

    .checkin-footer {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding-top: 15px;
      border-top: 1px solid #eee;
    }

    .checkin-rating {
      display: flex;
      align-items: center;
      color: #FF9800;
      font-weight: bold;
    }

    .checkin-actions {
      display: flex;
      gap: 15px;
    }

    .action-btn {
      background: none;
      border: none;
      color: #666;
      cursor: pointer;
      display: flex;
      align-items: center;
      font-size: 14px;
      transition: color 0.3s;
    }

    .action-btn i {
      margin-right: 5px;
    }

    .action-btn:hover {
      color: #6a11cb;
    }

    /* 分享弹窗 */
    /* 分享弹窗基础样式 */
    .share-modal {
      display: none;
      position: fixed;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      background-color: rgba(0, 0, 0, 0.5);
      z-index: 1000;
      align-items: center;
      justify-content: center;
    }

    .share-content {
      background-color: white;
      border-radius: 12px;
      width: 90%;
      max-width: 500px;
      padding: 25px;
      box-shadow: 0 10px 30px rgba(0, 0, 0, 0.15);
    }

    .share-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20px;
      padding-bottom: 15px;
      border-bottom: 1px solid #eee;
    }

    .share-title {
      font-size: 18px;
      font-weight: bold;
    }

    .close-modal {
      background: none;
      border: none;
      font-size: 20px;
      cursor: pointer;
      color: #999;
    }

    /* 店铺链接区域样式 */
    .share-link-section {
      margin-bottom: 20px;
    }

    .link-label {
      font-size: 14px;
      color: #666;
      margin-bottom: 8px;
    }

    .link-container {
      display: flex;
      gap: 8px;
      align-items: center;
    }

    #shopLinkInput {
      flex-grow: 1;
      padding: 8px 12px;
      border: 1px solid #ddd;
      border-radius: 6px;
      font-size: 13px;
      color: #333;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }

    .copy-btn {
      background-color: #6a11cb;
      color: white;
      border: none;
      padding: 8px 12px;
      border-radius: 6px;
      cursor: pointer;
      font-size: 13px;
      transition: background-color 0.3s;
    }

    .copy-btn:hover {
      background-color: #5a0dc8;
    }

    /* 操作按钮样式 */
    .share-actions {
      margin-top: 20px;
    }

    .share-btn {
      width: 100%;
      padding: 10px;
      border: none;
      border-radius: 6px;
      font-size: 16px;
      cursor: pointer;
      transition: all 0.3s;
    }

    .share-btn.publish {
      background: linear-gradient(45deg, #6a11cb 0%, #2575fc 100%);
      color: white;
    }

    .share-btn.publish:hover {
      background: linear-gradient(45deg, #5a0dc8 0%, #1a69e0 100%);
    }

    .share-btn.cancel {
      background-color: #f5f5f5;
      color: #666;
    }

    .share-btn.cancel:hover {
      background-color: #e6e6e6;
    }

    /* 空状态样式 */
    .empty-state {
      text-align: center;
      padding: 60px 20px;
      color: #999;
    }

    .empty-icon {
      font-size: 60px;
      margin-bottom: 20px;
      color: #ddd;
    }

    .empty-text {
      font-size: 18px;
      margin-bottom: 15px;
    }

    .empty-subtext {
      font-size: 14px;
      margin-bottom: 30px;
    }

    .empty-action {
      background: linear-gradient(45deg, #6a11cb 0%, #2575fc 100%);
      color: white;
      border: none;
      padding: 12px 25px;
      border-radius: 6px;
      cursor: pointer;
      font-size: 16px;
      transition: all 0.3s;
    }

    .empty-action:hover {
      background: linear-gradient(45deg, #5a0dc8 0%, #1a69e0 100%);
    }

    /* 评论区样式 */
    .comments-section {
      display: none;
      margin-top: 20px;
      padding-top: 20px;
      border-top: 1px solid #eee;
    }

    .comments-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 15px;
    }

    .comments-title {
      font-size: 16px;
      font-weight: bold;
      color: #333;
    }

    .comment-input {
      display: flex;
      margin-bottom: 20px;
    }

    .comment-avatar {
      width: 40px;
      height: 40px;
      border-radius: 50%;
      background-color: #eee;
      margin-right: 10px;
      flex-shrink: 0;
      display: flex;
      align-items: center;
      justify-content: center;
      color: #999;
    }

    .comment-textarea {
      flex-grow: 1;
      border: 1px solid #ddd;
      border-radius: 8px;
      padding: 10px;
      resize: none;
      font-family: inherit;
      font-size: 14px;
      height: 80px;
    }

    .comment-submit {
      background: linear-gradient(45deg, #6a11cb 0%, #2575fc 100%);
      color: white;
      border: none;
      padding: 8px 15px;
      border-radius: 6px;
      cursor: pointer;
      font-size: 14px;
      margin-left: 10px;
      align-self: flex-end;
    }

    .comments-list {
      margin-bottom: 20px;
    }

    .comment-item {
      display: flex;
      margin-bottom: 15px;
      padding-bottom: 15px;
      border-bottom: 1px solid #f0f0f0;
    }

    .comment-item:last-child {
      border-bottom: none;
      margin-bottom: 0;
      padding-bottom: 0;
    }

    .comment-author {
      font-weight: bold;
      font-size: 14px;
      margin-bottom: 5px;
    }

    .comment-time {
      font-size: 12px;
      color: #999;
      margin-bottom: 5px;
    }

    .comment-content {
      font-size: 14px;
      margin-bottom: 8px;
    }

    .comment-actions {
      display: flex;
      gap: 15px;
      font-size: 12px;
    }

    .comment-action {
      color: #666;
      cursor: pointer;
      display: flex;
      align-items: center;
    }

    .comment-action i {
      margin-right: 3px;
      font-size: 12px;
    }

    .comment-action:hover {
      color: #6a11cb;
    }

    /* 点赞状态样式 */
    .action-btn.liked i,
    .comment-action.liked i {
      color: #6a11cb; /* 已点赞的颜色 */
    }

    /* 返回按钮样式 */
    .back-btn-container {
      margin-bottom: 15px;
    }

    .back-btn {
      background: linear-gradient(45deg, #6a11cb 0%, #2575fc 100%);
      color: white;
      border: none;
      padding: 8px 16px;
      border-radius: 8px;
      cursor: pointer;
      font-size: 14px;
      display: flex;
      align-items: center;
      transition: all 0.3s;
    }

    .back-btn i {
      margin-right: 6px;
    }

    .back-btn:hover {
      background: linear-gradient(45deg, #5a0dc8 0%, #1a69e0 100%);
      transform: translateY(-2px);
    }

    /* 大图预览模态框 */
    #imagePreviewModal {
      position: fixed;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      background-color: rgba(0, 0, 0, 0.9);
      z-index: 2000;
      display: none;
      align-items: center;
      justify-content: center;
      padding: 20px;
    }

    #modalImage {
      max-width: 90%;
      max-height: 80vh;
      object-fit: contain;
      transition: transform 0.3s ease;
    }

    .modal-controls {
      position: absolute;
      top: 20px;
      right: 20px;
      display: flex;
      gap: 10px;
    }

    .modal-btn {
      width: 40px;
      height: 40px;
      border-radius: 50%;
      background-color: rgba(0, 0, 0, 0.5);
      color: white;
      border: none;
      display: flex;
      align-items: center;
      justify-content: center;
      cursor: pointer;
      transition: background-color 0.3s;
    }

    .modal-btn:hover {
      background-color: rgba(0, 0, 0, 0.7);
    }

    .modal-close {
      position: absolute;
      top: 20px;
      right: 20px;
      color: white;
      font-size: 30px;
      background: none;
      border: none;
      cursor: pointer;
      width: 40px;
      height: 40px;
      display: flex;
      align-items: center;
      justify-content: center;
    }

    /* 响应式设计 */
    @media (max-width: 768px) {
      .header-section {
        flex-direction: column;
        align-items: flex-start;
      }

      .user-info {
        flex-direction: column;
        margin-bottom: 20px;
        align-items: flex-start;
      }

      .user-avatar {
        margin-right: 0;
        margin-bottom: 15px;
      }

      .user-stats {
        flex-wrap: wrap;
      }

      .back-btn {
        margin-bottom: 15px;
        font-size: 13px;
        padding: 6px 12px;
      }

      /* 图片响应式调整 */
      .image-item {
        width: 80px;
        height: 80px;
      }

      .checkin-actions {
        flex-wrap: wrap;
        gap: 10px;
      }
    }

    /* 图片懒加载样式 */
    .image-placeholder {
      background-color: #f5f5f5;
      background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='40' height='40' viewBox='0 0 40 40'%3E%3Cpath d='M0 0h20v20H0V0zm10 17a7 7 0 1 0 0-14 7 7 0 0 0 0 14zm20 0a7 7 0 1 0 0-14 7 7 0 0 0 0 14zM10 37a7 7 0 1 0 0-14 7 7 0 0 0 0 14zm10-17h20v20H20V20zm10 17a7 7 0 1 0 0-14 7 7 0 0 0 0 14z' fill='%23ddd' fill-opacity='0.4'/%3E%3C/svg%3E");
      display: flex;
      align-items: center;
      justify-content: center;
    }

    .image-placeholder i {
      color: #ccc;
      font-size: 24px;
    }
  </style>
</head>
<body>
<!-- 内容区域 -->
<div class="content-container">
  <div class="back-btn-container">
    <button class="back-btn" onclick="goBackToMoments()">
      <i class="fas fa-arrow-left mr-2"></i> 返回朋友圈
    </button>
  </div>
  <!-- 头部区域 -->
  <div class="header-section">
    <div class="user-info">
      <div class="user-avatar">
        <img id="userAvatarImg" src="" alt="用户头像" class="w-full h-full rounded-full object-cover">
      </div>
      <div class="user-details">
        <h2 id="userNameElem">张小陌</h2>
        <div class="user-stats">
          <div class="stat-item">
            <i class="fas fa-store"></i> 打卡12家店铺
          </div>
          <div class="stat-item">
            <i class="fas fa-heart"></i> 获得38个赞
          </div>
          <div class="stat-item">
            <i class="fas fa-comment"></i> 收到15条评论
          </div>
        </div>
      </div>
    </div>
  </div>

  <!-- 时间线区域 -->
  <div class="timeline-section">
    <h2 class="section-title"><i class="fas fa-history"></i> 我的打卡记录</h2>

    <div class="timeline" id="timeline">
      <!-- 时间线内容将由JS动态生成 -->
    </div>
  </div>
</div>

<!-- 大图预览模态框 -->
<div id="imagePreviewModal">
  <button class="modal-close" id="closeModal">&times;</button>
  <div class="modal-controls">
    <button class="modal-btn" id="rotateLeft"><i class="fas fa-rotate-left"></i></button>
    <button class="modal-btn" id="rotateRight"><i class="fas fa-rotate-right"></i></button>
  </div>
  <img id="modalImage" src="" alt="图片预览">
</div>

<!-- 分享弹窗 -->
<div class="share-modal" id="shareModal">
  <div class="share-content">
    <div class="share-header">
      <h3 class="share-title">分享到朋友圈</h3>
      <button class="close-modal" onclick="closeShareModal()">&times;</button>
    </div>

    <!-- 店铺链接复制区域 -->
    <div class="share-link-section">
      <div class="link-label">店铺链接</div>
      <div class="link-container">
        <input type="text" id="shopLinkInput" value="" readonly>
        <button class="copy-btn" onclick="copyShopLink()">复制链接</button>
      </div>
    </div>

    <!-- 动态切换的操作按钮 -->
    <div class="share-actions">
      <button class="share-btn publish" id="publishBtn" onclick="confirmShare()">确定分享</button>
      <button class="share-btn cancel" id="cancelBtn" onclick="cancelShare()">取消分享</button>
    </div>
  </div>
</div>

<script src="../static/js/jquery-3.6.0.min.js"></script>
<script src="../static/js/jquery.cookie.min.js"></script>

<script>
  // 页面加载完成后执行
  $(document).ready(function () {
    let userId;
    let userName = $.cookie("username") || "张小陌"; // 用户名
    let user;
    let checkinList = [];   // 打卡数据
    let totalCheckinCount = 0;
    let totalLikes = 0;
    let totalReviews = 0;

    // 存储已点赞的打卡ID和评论ID
    let likedCheckinIds = new Set();  // 已点赞的打卡ID集合
    let likedCommentIds = new Set();  // 已点赞的评论ID集合

    // 图片预览相关变量
    let currentScale = 1;
    let currentRotate = 0;
    let currentImageIndex = 0;
    let currentImageList = [];

    //当前操作的打卡ID
    let currentCheckinId = null;

    // 1. 打开分享弹窗（传入打卡ID和分享状态isShared）
    window.openShareModal = function(checkinId, isShared) {
      currentCheckinId = checkinId;
      // 从打卡列表中获取当前打卡数据（需确保checkinList是全局可用的打卡数据数组）
      const checkinItem = checkinList.find(item => item.id === checkinId);
      console.log("checkinItem:", checkinItem)
      if (!checkinItem) return;

      // 动态生成店铺链接（替换为你的真实路由规则，如基于店铺ID）
      const shopId = checkinItem.shop?.id || 'unknown';
      const shopLink = `http://localhost:8080/homepage/goToDetail?id=${shopId}`; // 替换域名
      document.getElementById('shopLinkInput').value = shopLink;

      // 根据分享状态切换按钮显示
      if (isShared === 1) {
        document.getElementById('publishBtn').style.display = 'none'; // 隐藏"确定分享"
        document.getElementById('cancelBtn').style.display = 'block';  // 显示"取消分享"
      } else {
        document.getElementById('publishBtn').style.display = 'block'; // 显示"确定分享"
        document.getElementById('cancelBtn').style.display = 'none';  // 隐藏"取消分享"
      }

      // 显示弹窗
      document.getElementById('shareModal').style.display = 'flex';
    };

// 2. 关闭分享弹窗
    window.closeShareModal = function() {
      document.getElementById('shareModal').style.display = 'none';
      currentCheckinId = null; // 重置当前打卡ID
    };

// 3. 复制店铺链接
    window.copyShopLink = function() {
      const linkInput = document.getElementById('shopLinkInput');
      linkInput.select(); // 选中输入框内容
      document.execCommand('copy'); // 执行复制

      // 复制成功提示（2秒后恢复）
      const copyBtn = document.querySelector('.copy-btn');
      const originalText = copyBtn.textContent;
      copyBtn.textContent = '已复制!';
      setTimeout(() => {
        copyBtn.textContent = originalText;
      }, 2000);
    };

// 4. 确定分享（isShared=0时调用，标记为已分享）
    window.confirmShare = function() {
      if (!currentCheckinId) {
        closeShareModal();
        return;
      }

      // 调用后端接口更新分享状态（替换为你的真实接口地址）
      $.ajax({
        url: "/checkings/updateShareStatus", // 后端更新分享状态的接口
        type: "post",
        dataType: "json",
        data: {
          checkinId: currentCheckinId,
          isShared: 1, // 标记为已分享
          userId: userId // 全局用户ID，需确保已获取
        },
        success: function(res) {
          // 前端同步更新打卡数据的分享状态
          const checkinItem = checkinList.find(item => item.id == currentCheckinId);
          if (checkinItem) checkinItem.isShared = 1;
          renderTimeline(checkinList); // 重新渲染时间线，更新"分享"为"已分享"
          alert('分享成功！已同步到朋友圈');
        },
        error: function() {
          alert('分享接口请求失败，请重试');
        },
        complete: function() {
          closeShareModal(); // 无论成功失败，都关闭弹窗
        }
      });
    }

// 5. 取消分享（isShared=1时调用，标记为未分享）
    window.cancelShare = function() {
      if (!currentCheckinId) {
        closeShareModal();
        return;
      }

      // 调用后端接口取消分享（替换为你的真实接口地址）
      $.ajax({
        url: "/checkings/updateShareStatus", // 可复用同一个更新接口
        type: "post",
        dataType: "json",
        data: {
          checkinId: currentCheckinId,
          isShared: 0, // 标记为未分享
          userId: userId // 全局用户ID
        },
        success: function(res) {
          // 前端同步更新打卡数据的分享状态
          const checkinItem = checkinList.find(item => item.id == currentCheckinId);
          if (checkinItem) checkinItem.isShared = 0;
          renderTimeline(checkinList); // 重新渲染时间线，更新"已分享"为"分享"
          alert('取消分享成功！已从朋友圈移除');
        },
        error: function() {
          alert('取消分享接口请求失败，请重试');
        },
        complete: function() {
          closeShareModal(); // 无论成功失败，都关闭弹窗
        }
      });
    }

    // 点击返回朋友圈
    window.goBackToMoments = function() {
      window.location.href = "/moments";
    };

    // 1. 获取用户ID并加载数据
    function getUserIdByName() {
      $.ajax({
        url: "/checkings/getUserIdByName",
        type: "post",
        dataType: "json",
        data: { userName: userName },
        success: function (res) {
          userId = res.data;
          getCheckinsByUserId().then(() => {
            findUserInfoByUserId();
            getUserLikedCheckins();
          });
        },
        error: function () {
          console.log("获取用户id错误");
          renderTimeline([]);
        }
      });
    }

    // 通过用户id获取用户信息
    function findUserInfoByUserId(){
      $.ajax({
        url:"/checkings/findUserInfoByUserId",
        type:"post",
        dataType:"json",
        data:{
          userId:userId
        },
        success:function (res){
          user = res.data;

          // 加载用户头像
          const avatarImg = document.getElementById('userAvatarImg');
          if (user && user.icon) {
            avatarImg.src = user.icon;
          } else {
            avatarImg.src = '../static/images/default-avatar.jpg';
          }

          // 加载用户名
          const userNameElem = document.getElementById('userNameElem');
          if (user && user.username) {
            userNameElem.textContent = user.username;
          } else {
            userNameElem.textContent = '未知用户';
          }
        },
        error:function(){
          console.log("用户id：", userId)
          alert("通过用户id获取用户信息出错...");
        }
      })
    }

    // 2. 获取打卡数据（返回Promise用于链式调用）
    function getCheckinsByUserId() {
      return new Promise((resolve) => {
        if (userId) {
          $.ajax({
            url: "/checkings/getCheckinsByUserId",
            type: "post",
            dataType: "json",
            data: { Uid: userId },
            success: function (res) {
              console.log("个人用户的打卡记录", res)

              checkinList = res.data || [];
              totalCheckinCount = checkinList.length;
              totalLikes = checkinList.reduce((sum, item) => sum + (item.likes || 0), 0);
              totalReviews = checkinList.reduce((sum, item) => sum + (item.reviews || 0), 0);
              renderTimeline(checkinList);
              updateUserStats(totalCheckinCount, totalLikes, totalReviews);
              resolve();
            },
            error: function () {
              console.log("获取用户打卡信息错误");
              renderTimeline([]);
              resolve();
            }
          });
        } else {
          resolve();
        }
      });
    }

    // 3. 渲染打卡时间线（含点赞状态和多图展示）
    // function renderTimeline(data) {
    //   const timeline = document.getElementById('timeline');
    //   let html = '';
    //
    //   if (data.length === 0) {
    //     html = `
    //       <div class="empty-state">
    //           <div class="empty-icon"><i class="fas fa-calendar-times"></i></div>
    //           <div class="empty-text">暂无打卡记录</div>
    //           <div class="empty-subtext">快去探索并打卡你喜欢的店铺吧</div>
    //           <button class="empty-action" onclick="goToExplore()">去探索</button>
    //       </div>
    //     `;
    //     timeline.innerHTML = html;
    //     updateUserStats(0, 0, 0);
    //     return;
    //   }
    //
    //   data.forEach(item => {
    //     // 判断当前打卡是否已被用户点赞
    //     const isCheckinLiked = likedCheckinIds.has(item.id);
    //
    //     // 解析图片URLs（从字符串转数组）
    //     let imgsArray = [];
    //     if (item.imgsUrls) {
    //       try {
    //         const cleanedImgsUrls = item.imgsUrls.replace(/\\"/g, '"');
    //         imgsArray = JSON.parse(cleanedImgsUrls);
    //       } catch (e) {
    //         imgsArray = [item.imgsUrls];
    //       }
    //     }
    //
    //     // 生成图片预览HTML（左对齐正方形网格）
    //     let imagesHtml = '';
    //     if (imgsArray && imgsArray.length > 0) {
    //       imagesHtml = `<div class="image-container">`;
    //       imgsArray.forEach((imgUrl, index) => {
    //         imagesHtml += `
    //           <div class="image-item" data-checkin-id="${item.id}" data-img-index="${index}">
    //             <div class="image-placeholder">
    //               <i class="fas fa-image"></i>
    //             </div>
    //             <img src="" data-src="${imgUrl}" alt="打卡图片 ${index + 1}" class="lazy-load">
    //             <div class="image-overlay">
    //               <i class="fas fa-search-plus"></i>
    //             </div>
    //           </div>
    //         `;
    //       });
    //       imagesHtml += `</div>`;
    //     } else {
    //       // 如果没有打卡图片，显示店铺头像作为默认图
    //       imagesHtml = `
    //         <div class="checkin-images">
    //             <img
    //                 src="${item.shop?.avatarUrl || '../static/images/default-shop.jpg'}"
    //                 class="checkin-image"
    //                 alt="${item.shop?.name || '店铺图片'}"
    //             >
    //         </div>
    //       `;
    //     }
    //
    //     const shareText = item.isShared ? '已分享' : '分享';
    //
    //     const commentsHtml = `
    //       <div class="comments-section" id="commentsSection-${item.id}" style="display: none;">
    //         <div class="comments-header">
    //           <div class="comments-title">评论 (${item.reviews || 0})</div>
    //         </div>
    //
    //         <div class="comment-input">
    //           <div class="comment-avatar">${userName.charAt(0)}</div>
    //           <textarea class="comment-textarea" placeholder="写下你的评论..." id="commentInput-${item.id}"></textarea>
    //           <button class="comment-submit" onclick="submitComment(${item.id})">发布</button>
    //         </div>
    //         <div class="comments-list" id="commentsList-${item.id}">
    //           <div class="empty-state" style="padding: 30px 20px;">
    //             <div class="empty-text" style="font-size: 14px;">加载中...</div>
    //           </div>
    //         </div>
    //       </div>
    //     `;
    //
    //     html += `
    //       <div class="timeline-item">
    //         <div class="checkin-card">
    //           <div class="checkin-header">
    //             <div class="shop-name">${item.shop?.name || '未知店铺'}</div>
    //             <div class="checkin-date">${formatDate(item.createdAt)}</div>
    //           </div>
    //
    //           ${imagesHtml}
    //
    //           <div class="checkin-content">
    //             ${item.context || '暂无描述'}
    //           </div>
    //
    //           <div class="checkin-footer">
    //             <div class="checkin-rating">
    //               <i class="fas fa-star"></i> ${item.shop?.rating || 0}
    //             </div>
    //             <div class="checkin-actions">
    //               <button class="action-btn ${isCheckinLiked ? 'liked' : ''}" onclick="toggleCheckinLike(${item.id})">
    //                 <i class="fas fa-heart"></i> ${item.likes || 0}
    //               </button>
    //               <button class="action-btn" onclick="toggleComments(${item.id})">
    //                 <i class="fas fa-comment"></i> ${item.reviews || 0}
    //               </button>
    //               <button class="action-btn ${item.isShared ? 'shared' : ''}" onclick="openShareModal(${item.id})">
    //                 <i class="fas fa-share-alt"></i> ${shareText}
    //               </button>
    //             </div>
    //           </div>
    //
    //           ${commentsHtml}
    //         </div>
    //       </div>
    //     `;
    //   });
    //
    //   timeline.innerHTML = html;
    //
    //   // 初始化图片懒加载
    //   initImageLazyLoad();
    //
    //   // 绑定图片点击事件，实现大图预览
    //   bindImagePreviewEvents();
    // }

    function renderTimeline(data) {
      const timeline = document.getElementById('timeline');
      let html = '';

      if (data.length === 0) {
        html = `
      <div class="empty-state">
          <div class="empty-icon"><i class="fas fa-calendar-times"></i></div>
          <div class="empty-text">暂无打卡记录</div>
          <div class="empty-subtext">快去探索并打卡你喜欢的店铺吧</div>
          <button class="empty-action" onclick="goToExplore()">去探索</button>
      </div>
    `;
        timeline.innerHTML = html;
        updateUserStats(0, 0, 0);
        return;
      }

      data.forEach(item => {
        // 判断当前打卡是否已被用户点赞
        const isCheckinLiked = likedCheckinIds.has(item.id);

        // 解析图片URLs（从字符串转数组）
        let imgsArray = [];
        if (item.imgsUrls) {
          try {
            const cleanedImgsUrls = item.imgsUrls.replace(/\\"/g, '"');
            imgsArray = JSON.parse(cleanedImgsUrls);
          } catch (e) {
            imgsArray = [item.imgsUrls];
          }
        }

        // 生成图片预览HTML（左对齐正方形网格）
        let imagesHtml = '';
        if (imgsArray && imgsArray.length > 0) {
          imagesHtml = `<div class="image-container">`;
          imgsArray.forEach((imgUrl, index) => {
            imagesHtml += `
          <div class="image-item" data-checkin-id="${item.id}" data-img-index="${index}">
            <div class="image-placeholder">
              <i class="fas fa-image"></i>
            </div>
            <img src="" data-src="${imgUrl}" alt="打卡图片 ${index + 1}" class="lazy-load">
            <div class="image-overlay">
              <i class="fas fa-search-plus"></i>
            </div>
          </div>
        `;
          });
          imagesHtml += `</div>`;
        } else {
          // 如果没有打卡图片，显示店铺头像作为默认图
          imagesHtml = `
        <div class="checkin-images">
            <img
                src="${item.shop?.avatarUrl || '../static/images/default-shop.jpg'}"
                class="checkin-image"
                alt="${item.shop?.name || '店铺图片'}"
            >
        </div>
      `;
        }

        // 分享状态文本（已分享/分享）
        const shareText = item.isShared ? '已分享' : '分享';

        const commentsHtml = `
      <div class="comments-section" id="commentsSection-${item.id}" style="display: none;">
        <div class="comments-header">
          <div class="comments-title">评论 (${item.reviews || 0})</div>
        </div>

        <div class="comment-input">
          <div class="comment-avatar">${userName.charAt(0)}</div>
          <textarea class="comment-textarea" placeholder="写下你的评论..." id="commentInput-${item.id}"></textarea>
          <button class="comment-submit" onclick="submitComment(${item.id})">发布</button>
        </div>
        <div class="comments-list" id="commentsList-${item.id}">
          <div class="empty-state" style="padding: 30px 20px;">
            <div class="empty-text" style="font-size: 14px;">加载中...</div>
          </div>
        </div>
      </div>
    `;

        html += `
      <div class="timeline-item">
        <div class="checkin-card">
          <div class="checkin-header">
            <div class="shop-name">${item.shop?.name || '未知店铺'}</div>
            <div class="checkin-date">${formatDate(item.createdAt)}</div>
          </div>

          ${imagesHtml}

          <div class="checkin-content">
            ${item.context || '暂无描述'}
          </div>

          <div class="checkin-footer">
            <div class="checkin-rating">
              <i class="fas fa-star"></i> ${item.shop?.rating || 0}
            </div>
            <div class="checkin-actions">
              <button class="action-btn ${isCheckinLiked ? 'liked' : ''}" onclick="toggleCheckinLike(${item.id})">
                <i class="fas fa-heart"></i> ${item.likes || 0}
              </button>
              <button class="action-btn" onclick="toggleComments(${item.id})">
                <i class="fas fa-comment"></i> ${item.reviews || 0}
              </button>
              <!-- 核心修改：分享按钮传入打卡ID和分享状态isShared -->
              <button class="action-btn ${item.isShared ? 'shared' : ''}" onclick="openShareModal(${item.id}, ${item.isShared})">
                <i class="fas fa-share-alt"></i> ${shareText}
              </button>
            </div>
          </div>

          ${commentsHtml}
        </div>
      </div>
    `;
      });

      timeline.innerHTML = html;

      // 初始化图片懒加载
      initImageLazyLoad();

      // 绑定图片点击事件，实现大图预览
      bindImagePreviewEvents();
    }

    // 图片懒加载实现
    function initImageLazyLoad() {
      const lazyImages = document.querySelectorAll('.lazy-load');

      if ('IntersectionObserver' in window) {
        const imageObserver = new IntersectionObserver((entries, observer) => {
          entries.forEach(entry => {
            if (entry.isIntersecting) {
              const image = entry.target;
              image.src = image.dataset.src;
              image.classList.remove('lazy-load');
              imageObserver.unobserve(image);

              image.onload = function() {
                const placeholder = image.previousElementSibling;
                if (placeholder && placeholder.classList.contains('image-placeholder')) {
                  placeholder.style.display = 'none';
                }
              };
            }
          });
        });

        lazyImages.forEach(image => {
          imageObserver.observe(image);
        });
      } else {
        lazyImages.forEach(image => {
          image.src = image.dataset.src;
          image.classList.remove('lazy-load');
          const placeholder = image.previousElementSibling;
          if (placeholder && placeholder.classList.contains('image-placeholder')) {
            placeholder.style.display = 'none';
          }
        });
      }
    }

    // 绑定图片预览事件
    function bindImagePreviewEvents() {
      // 点击图片打开预览模态框
      document.querySelectorAll('.image-item').forEach(item => {
        item.addEventListener('click', function() {
          const checkinId = this.getAttribute('data-checkin-id');
          const imgIndex = parseInt(this.getAttribute('data-img-index'));

          const checkinItem = checkinList.find(item => item.id == checkinId);
          if (!checkinItem) return;

          try {
            const cleanedImgsUrls = checkinItem.imgsUrls.replace(/\\"/g, '"');
            currentImageList = JSON.parse(cleanedImgsUrls);
          } catch (e) {
            currentImageList = [checkinItem.imgsUrls];
          }

          currentScale = 1;
          currentRotate = 0;
          currentImageIndex = imgIndex;

          const modalImage = document.getElementById('modalImage');
          modalImage.src = currentImageList[currentImageIndex];
          modalImage.style.transform = 'scale(1) rotate(0deg)';

          document.getElementById('imagePreviewModal').style.display = 'flex';
        });
      });

      // 关闭预览模态框
      document.getElementById('closeModal').addEventListener('click', function() {
        document.getElementById('imagePreviewModal').style.display = 'none';
      });

      // 点击模态框背景关闭
      document.getElementById('imagePreviewModal').addEventListener('click', function(e) {
        if (e.target === this) {
          this.style.display = 'none';
        }
      });

      // 图片旋转功能
      document.getElementById('rotateLeft').addEventListener('click', function() {
        currentRotate -= 90;
        updateModalImageTransform();
      });

      document.getElementById('rotateRight').addEventListener('click', function() {
        currentRotate += 90;
        updateModalImageTransform();
      });

      // 滚轮放大/缩小图片
      document.getElementById('modalImage').addEventListener('wheel', function(e) {
        e.preventDefault(); // 阻止滚轮默认行为（如页面滚动）
        if (e.deltaY < 0) {
          currentScale = Math.min(currentScale + 0.1, 3); // 向上滚动→放大
        } else {
          currentScale = Math.max(currentScale - 0.1, 0.5); // 向下滚动→缩小
        }
        updateModalImageTransform();
      });

      // 键盘导航
      document.addEventListener('keydown', function(e) {
        const modal = document.getElementById('imagePreviewModal');
        if (modal.style.display !== 'flex') return;

        if (e.key === 'Escape') {
          modal.style.display = 'none';
        } else if (e.key === 'ArrowLeft') {
          currentImageIndex = (currentImageIndex - 1 + currentImageList.length) % currentImageList.length;
          updateModalImageSource();
        } else if (e.key === 'ArrowRight') {
          currentImageIndex = (currentImageIndex + 1) % currentImageList.length;
          updateModalImageSource();
        } else if (e.key === 'ArrowUp') {
          currentScale = Math.min(currentScale + 0.1, 3);
          updateModalImageTransform();
        } else if (e.key === 'ArrowDown') {
          currentScale = Math.max(currentScale - 0.1, 0.5);
          updateModalImageTransform();
        } else if (e.key === 'r' || e.key === 'R') {
          currentRotate = 0;
          updateModalImageTransform();
        }
      });
    }

    // 更新模态框图片变换
    function updateModalImageTransform() {
      const modalImage = document.getElementById('modalImage');
      modalImage.style.transform = `scale(${currentScale}) rotate(${currentRotate}deg)`;
    }

    // 更新模态框图片源
    function updateModalImageSource() {
      const modalImage = document.getElementById('modalImage');
      modalImage.src = currentImageList[currentImageIndex];
      modalImage.style.transform = `scale(${currentScale}) rotate(0deg)`;
      currentRotate = 0;
    }

    // 4. 获取评论列表
    function getCommentsByCheckinId(checkinId) {
      const commentsListElem = document.getElementById(`commentsList-${checkinId}`);
      commentsListElem.innerHTML = `
          <div class="empty-state" style="padding: 30px 20px;">
              <div class="empty-text" style="font-size: 14px;">加载中...</div>
          </div>
      `;

      $.ajax({
        url: "/checkings/getCommentsByCheckinId",
        type: "post",
        dataType: "json",
        data: { checkinId: checkinId },
        success: function (res) {
          const comments = res.data || [];
          if (comments.length > 0) {
            commentsListElem.innerHTML = renderCommentList(comments, checkinId);
          } else {
            commentsListElem.innerHTML = `
                      <div class="empty-state" style="padding: 30px 20px;">
                          <div class="empty-text" style="font-size: 14px;">暂无评论，快来发表第一条评论吧</div>
                      </div>
                  `;
          }
        },
        error: function () {
          commentsListElem.innerHTML = `
                  <div class="empty-state" style="padding: 30px 20px; color: #ff4d4f;">
                      <div class="empty-text" style="font-size: 14px;">评论加载失败，请重试</div>
                  </div>
              `;
        }
      });
    }

    // 5. 渲染子评论
    function getChildComments(checkinId, parentId) {
      const childContainer = document.getElementById(`childComments-${parentId}`);
      if (!childContainer) return;

      $.ajax({
        url: "/checkings/getChildrenCommentsByParentId",
        type: "post",
        dataType: "json",
        data: { parentId: parentId },
        success: function (res) {
          const childComments = res.data || [];
          if (childComments.length > 0) {
            childContainer.innerHTML = renderCommentList(childComments, checkinId);
          } else {
            childContainer.innerHTML = `
        <div class="empty-state" style="padding: 15px 0;">
          <div class="empty-text" style="font-size: 13px;">暂无回复</div>
        </div>
      `;
          }
        },
        error: function () {
          childContainer.innerHTML = `
      <div class="empty-state" style="padding: 15px 0; color: #ff4d4f;">
        <div class="empty-text" style="font-size: 13px;">加载回复失败，请重试</div>
      </div>
    `;
        }
      });
    }

    // 6. 渲染评论列表
    function renderCommentList(comments, checkinId) {
      let commentHtml = '';
      comments.forEach(comment => {
        const isCommentLiked = likedCommentIds.has(comment.id);

        commentHtml += `
          <div class="comment-item" id="comment-${comment.id}">
            <div class="comment-avatar">${comment.user.username?.charAt(0) || '未'}</div>
            <div class="comment-body">
              <div class="comment-author">${comment.user.username || '匿名用户'}</div>
              <div class="comment-time">${formatDate(comment.createdAt)}</div>
              <div class="comment-content">${comment.content || '无内容'}</div>
              <div class="comment-actions">
                <div class="comment-action ${isCommentLiked ? 'liked' : ''}" onclick="toggleCommentLike(${checkinId}, ${comment.id})">
                  <i class="fas fa-heart"></i> ${comment.likeCount || 0}
                </div>
                ${comment.parentId ? '' : `
                  <div class="comment-action" onclick="replyToComment(${checkinId}, ${comment.id}, '${comment.user.username || '匿名用户'}')">
                    <i class="fas fa-reply"></i> 回复
                  </div>
                `}
                ${comment.parentId ? '' : `
                  <div class="comment-action" onclick="toggleChildComments(${checkinId}, ${comment.id})">
                    <i class="fas fa-comment-dots"></i> 查看回复
                  </div>
                `}
              </div>
              <div class="child-comments" id="childComments-${comment.id}" style="display: none; margin-left: 20px; padding-top: 10px;">
                <div class="empty-state" style="padding: 15px 0;">
                  <div class="empty-text" style="font-size: 13px;">加载中...</div>
                </div>
              </div>
            </div>
          </div>
        `;
      });
      return commentHtml;
    }

    // 7. 更新顶部用户统计
    function updateUserStats(checkinCount, likes, reviews) {
      document.querySelectorAll('.stat-item')[0].innerHTML = `<i class="fas fa-store"></i> 打卡${checkinCount}家店铺`;
      document.querySelectorAll('.stat-item')[1].innerHTML = `<i class="fas fa-heart"></i> 获得${likes}个赞`;
      document.querySelectorAll('.stat-item')[2].innerHTML = `<i class="fas fa-comment"></i> 收到${reviews}条评论`;
    }

    // 8. 日期格式化
    function formatDate(dateStr) {
      if (!dateStr) return '未知时间';
      let date = new Date(dateStr);
      if (isNaN(date.getTime())) {
        date = new Date(Number(dateStr));
      }

      const now = new Date();
      const diffMs = now - date;
      const diffMins = Math.floor(diffMs / 60000);
      const diffHours = Math.floor(diffMins / 60);
      const diffDays = Math.floor(diffHours / 24);

      if (diffMins < 60) {
        return `${diffMins}分钟前`;
      } else if (diffHours < 24) {
        return `${diffHours}小时前`;
      } else if (diffDays < 30) {
        return `${diffDays}天前`;
      } else {
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        return `${year}-${month}-${day}`;
      }
    }

    // 9. 切换评论区显示/隐藏
    window.toggleComments = function(checkinId) {
      const commentsSection = document.getElementById(`commentsSection-${checkinId}`);
      const commentsListElem = document.getElementById(`commentsList-${checkinId}`);

      if (!commentsSection || !commentsListElem) return;

      if (commentsSection.style.display === 'none') {
        commentsSection.style.display = 'block';
        const isLoaded = !commentsListElem.innerHTML.includes('加载中...') &&
                !commentsListElem.innerHTML.includes('评论加载失败');
        if (!isLoaded) {
          getUserLikedComments(checkinId).then(() => {
            getCommentsByCheckinId(checkinId);
          });
        }
      } else {
        commentsSection.style.display = 'none';
      }
    }

    // 10. 切换子评论显示/隐藏
    window.toggleChildComments = function(checkinId, parentId) {
      const childContainer = document.getElementById(`childComments-${parentId}`);
      if (!childContainer) return;

      if (childContainer.style.display === 'none') {
        childContainer.style.display = 'block';
        const isLoaded = !childContainer.innerHTML.includes('加载中...') &&
                !childContainer.innerHTML.includes('暂无回复');
        if (!isLoaded) {
          getChildComments(checkinId, parentId);
        }
      } else {
        childContainer.style.display = 'none';
      }
    };

    // 11. 提交评论
    window.submitComment = function(checkinId) {
      const inputElem = document.getElementById(`commentInput-${checkinId}`);
      const commentContent = inputElem.value.trim();
      const commentsListElem = document.getElementById(`commentsList-${checkinId}`);

      if (!commentContent) {
        alert('请输入评论内容');
        return;
      }

      let isReply = false;
      let parentId = null;
      let targetUserName = '';

      if (commentContent.startsWith('@')) {
        isReply = true;
        parentId = inputElem.getAttribute('data-reply-to');
        targetUserName = inputElem.getAttribute('data-target-user');
        if (!parentId) {
          isReply = false;
        }
      }

      const tempComment = {
        id: Date.now(),
        user: { username: userName },
        content: commentContent,
        createdAt: new Date().toISOString(),
        likeCount: 0,
        parentId: parentId
      };

      const currentHtml = commentsListElem.innerHTML;
      if (currentHtml.includes('暂无评论') || currentHtml.includes('加载中...') || currentHtml.includes('加载失败')) {
        commentsListElem.innerHTML = renderCommentList([tempComment], checkinId);
      } else {
        commentsListElem.innerHTML += renderCommentList([tempComment], checkinId);
      }
      inputElem.value = '';
      inputElem.removeAttribute('data-reply-to');
      inputElem.removeAttribute('data-target-user');

      const url = isReply ? "/checkings/replyComment" : "/checkings/addComment";

      $.ajax({
        url: url,
        type: "post",
        dataType: "json",
        data: {
          checkinId: checkinId,
          userId: userId,
          content: commentContent,
          parentId: isReply ? parentId : null
        },
        success: function (res) {
          getCommentsByCheckinId(checkinId);
          if (res.data) {
            updateCheckinReviewCount(checkinId, res.data);
          }
        },
        error: function () {
          const tempElem = document.getElementById(`comment-${tempComment.id}`);
          if (tempElem) tempElem.remove();
          alert('评论提交失败，请重试');
        }
      });
    }

    // 12. 评论点赞/取消点赞切换
    window.toggleCommentLike = function(checkinId, commentId) {
      const isLiked = likedCommentIds.has(commentId);
      const commentElem = document.getElementById(`comment-${commentId}`);
      if (!commentElem) return;

      const likeBtnElem = commentElem.querySelector('.comment-action .fa-heart').parentElement;
      const likeCountElem = likeBtnElem.querySelector('.fa-heart').nextSibling;
      const currentLikes = parseInt(likeCountElem.textContent.trim()) || 0;

      if (isLiked) {
        likeBtnElem.classList.remove('liked');
        likeCountElem.textContent = ` ${currentLikes - 1}`;
        likedCommentIds.delete(commentId);
      } else {
        likeBtnElem.classList.add('liked');
        likeCountElem.textContent = ` ${currentLikes + 1}`;
        likedCommentIds.add(commentId);
      }

      const url = isLiked ? "/checkings/cancelCommentLike" : "/checkings/likeComment";
      $.ajax({
        url: url,
        type: "post",
        dataType: "json",
        data: {
          commentId: commentId,
          userId: userId
        },
        success: function(res){
        },
        error: function () {
          if (isLiked) {
            likeBtnElem.classList.add('liked');
            likeCountElem.textContent = ` ${currentLikes}`;
            likedCommentIds.add(commentId);
          } else {
            likeBtnElem.classList.remove('liked');
            likeCountElem.textContent = ` ${currentLikes}`;
            likedCommentIds.delete(commentId);
          }
          alert('操作失败，请重试');
        }
      });
    }

    // 13. 回复评论
    window.replyToComment = function(checkinId, commentId, targetUserName) {
      const inputElem = document.getElementById(`commentInput-${checkinId}`);
      const commentsSection = document.getElementById(`commentsSection-${checkinId}`);

      if (!inputElem || !commentsSection) return;

      if (commentsSection.style.display === 'none') {
        commentsSection.style.display = 'block';
        const commentsListElem = document.getElementById(`commentsList-${checkinId}`);
        const isLoaded = !commentsListElem.innerHTML.includes('加载中...') &&
                !commentsListElem.innerHTML.includes('评论加载失败');
        if (!isLoaded) {
          getCommentsByCheckinId(checkinId);
        }
      }

      inputElem.value = `@${targetUserName} `;
      inputElem.setAttribute('data-reply-to', commentId);
      inputElem.setAttribute('data-target-user', targetUserName);
      inputElem.focus();
      inputElem.selectionStart = inputElem.selectionEnd = inputElem.value.length;
    };

    // 14. 打卡点赞/取消点赞切换
    window.toggleCheckinLike = function(checkinId) {
      const isLiked = likedCheckinIds.has(checkinId);
      const likeBtnElem = document.querySelector(`.timeline-item:has(#commentsSection-${checkinId}) .checkin-actions .fa-heart`).parentElement;
      const likeCountElem = likeBtnElem.querySelector('.fa-heart').nextSibling;
      const currentLikes = parseInt(likeCountElem.textContent.trim()) || 0;

      if (isLiked) {
        likeBtnElem.classList.remove('liked');
        likeCountElem.textContent = ` ${currentLikes - 1}`;
        likedCheckinIds.delete(checkinId);
        totalLikes--;
      } else {
        likeBtnElem.classList.add('liked');
        likeCountElem.textContent = ` ${currentLikes + 1}`;
        likedCheckinIds.add(checkinId);
        totalLikes++;
      }

      updateUserStats(totalCheckinCount, totalLikes, totalReviews);

      const url = isLiked ? "/checkings/cancelCheckinLike" : "/checkings/likeCheckin";
      $.ajax({
        url: url,
        type: "post",
        dataType: "json",
        data: {
          checkinId: checkinId,
          userId: userId
        },
        success: function(res) {
          if (res.success && res.data?.newLikeCount) {
            likeCountElem.textContent = ` ${res.data.newLikeCount}`;
            totalLikes = res.data.newTotalLikeCount || totalLikes;
            updateUserStats(totalCheckinCount, totalLikes, totalReviews);
          }
        },
        error: function () {
          if (isLiked) {
            likeBtnElem.classList.add('liked');
            likeCountElem.textContent = ` ${currentLikes}`;
            likedCheckinIds.add(checkinId);
            totalLikes++;
          } else {
            likeBtnElem.classList.remove('liked');
            likeCountElem.textContent = ` ${currentLikes}`;
            likedCheckinIds.delete(checkinId);
            totalLikes--;
          }
          updateUserStats(totalCheckinCount, totalLikes, totalReviews);
          alert('操作失败，请重试');
        }
      });
    }

    // 15. 更新打卡的评论数
    function updateCheckinReviewCount(checkinId, newReviewCount) {
      if (!newReviewCount) return;
      const reviewBtnElem = document.querySelector(`.timeline-item:has(#commentsSection-${checkinId}) .checkin-actions .fa-comment`).nextSibling;
      if (reviewBtnElem) {
        reviewBtnElem.textContent = ` ${newReviewCount}`;
      }
      const commentTitleElem = document.querySelector(`#commentsSection-${checkinId} .comments-title`);
      if (commentTitleElem) {
        commentTitleElem.textContent = `评论 (${newReviewCount})`;
      }
      totalReviews = newReviewCount;
      updateUserStats(totalCheckinCount, totalLikes, totalReviews);
    }

    // 16. 查询用户已点赞的打卡ID列表
    function getUserLikedCheckins() {
      $.ajax({
        url: "/checkings/getUserLikedCheckins",
        type: "post",
        dataType: "json",
        data: { userId: userId },
        success: function (res) {
          if (res.data) {
            likedCheckinIds = new Set(res.data);
            renderTimeline(checkinList);
          }
        }
      });
    }

    // 17. 查询用户已点赞的评论ID列表
    function getUserLikedComments(checkinId) {
      return new Promise((resolve) => {
        $.ajax({
          url: "/checkings/getUserLikedComments",
          type: "post",
          dataType: "json",
          data: {
            userId: userId,
            checkinId: checkinId
          },
          success: function (res) {
            if (res.data) {
              likedCommentIds = new Set(res.data);
            }
            resolve();
          },
          error: function () {
            resolve();
          }
        });
      });
    }

    // 初始化加载
    getUserIdByName();
  });
</script>

</body>
</html>